<?php

function isValidEmail($email) {
    return preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email);
}

function greengar_send_mail($to, $subject, $message) {
    $from = "usersystem-noreply@greengar.com";
    $headers = "From:" . $from;
    mail($to, $subject, $message, $headers);
}

function get_array_from_keywords($string) {
    $blacklist2 = '\'/\\"*& ?#%^(){}[]~?<>;|¬`@-+=';
//    $blacklist2 = '@';
    for ($n = 0; $n < strlen($blacklist2); $n++) {
        $pos = strpos($string, $blacklist2[$n]);
        if ($pos != false) {
            $string = str_replace($blacklist2[$n], ' ', $string);
        }
    }
    while (strpos($string, '  ')) {
        $string = str_replace('  ', ' ', $string);
    }
    $keywords = explode(' ', $string);
    $keywords = array_unique($keywords);
    return $keywords;
}

function build_like_query($field, $keywords) {
    $parts = array();
    foreach ($keywords as $keyword) {
//        if(strlen($keyword) <= 0) {
//            continue;
//        }
        $keyword = mysql_real_escape_string($keyword);
        $parts[] = " ($field LIKE '%$keyword%') ";
    }
    $query = NULL;
    if (count($parts) > 0) {
        $query .= "(";
        $query .= "$parts[0]";
    }

    for ($n = 1; $n < count($parts); $n++) {
        $query .= " AND $parts[$n]";
    }
    if ($query !== NULL) {
        $query .= ")";
    }
    return $query;
}

function export_result($code, $result) {
    return array(
        'status' => $code,
        'result' => $result
    );
}

function genRandomString($length = 8) {
//    $time = time();
    $characters = 'bcfghjklmnprstvwxyz';

    $string = '';

    while (strlen($string) < $length) {
        $index = mt_rand(0, strlen($characters));
        $string .= $characters[$index];
    }
//    echo (time() - $time);
    return $string;
}

define('REGISTER', 'register');
define('REGISTER_HMAC', 'yQ%)^fi<FnceBz1$>>D!wwhX&?2OhJK|C;R;?X6>)/ruX2)}^p|f+6rkn14A=mbx');
define('FACEBOOK_LOGIN', 'facebook_login');
define('FACEBOOK_LOGIN_HMAC', 'facebook_login');
define('RESET_PASSWORD', 'reset_password');
define('RESET_PASSWORD_HMAC', 'reset_password');
define('UPLOAD', 'upload');
define('UPLOAD_HMAC', 'Ho9cYabIgiD0KaHo');

function get_hmac_key($case) {
    switch ($case) {
        case REGISTER:
            return REGISTER_HMAC;
        case FACEBOOK_LOGIN:
            return FACEBOOK_LOGIN_HMAC;
        case RESET_PASSWORD:
            return RESET_PASSWORD_HMAC;
        case UPLOAD:
            return UPLOAD_HMAC;
    }
}

function compute_hash($base_string, $case) {
    $key = get_hmac_key($case);
    return base64_encode(hash_hmac('sha1', $base_string, $key, true));
}

?>
